package com.SQL;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class DBUtil {
	//jdbc:mysql://localhost:3306/mysql_1?useSSL=false&user=root&password=root&characterEncoding=utf8
	private final static String URL =  "jdbc:mysql://localhost:3306/mysql_1?characterEncoding=utf8";
	private final static String USER = "root";
	private final static String PAW = "root";
	public static Connection col = null;
	public static PreparedStatement ps = null;
	public static Connection getConnection() throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver");
		return DriverManager.getConnection(URL, USER, PAW);
	}
	public static void closeAll(ResultSet rs, Statement sm, Connection col) throws SQLException {
		if(rs != null) {
			rs.close();
		}
		if(sm != null) {
			sm.close();
		}
		if(col != null) {
			col.close();
		}
	}
	public static boolean executeProject(String sql, ArrayList<Object> al) throws SQLException {
		try {
			ps = getConnection().prepareStatement(sql);
			for(int i = 0; i < al.size(); i++) {
				ps.setObject(i + 1, al.get(i));
			}
			return ps.executeUpdate() > 0? true: false;
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			closeAll(null, ps, col);
		}
		return false;
	}
	public static ResultSet enquryProject(String sql, ArrayList<Object> al) throws ClassNotFoundException, SQLException {
		ps = getConnection().prepareStatement(sql);
		if(al != null) {
			for(int i = 0; i < al.size(); i++) {
				ps.setObject(i + 1, al.get(i));
			}
		}
		return ps.executeQuery();
	}
}
